package com.hyj.serve.manage.entity.firewall;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.huitian.mybatis.plus.util.MPUtils;
import lombok.Data;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

/**
 * @author HeYuJie
 * @date 2022/6/6
 */
@Data
public class ServiceRule extends RuleItem {

    public static final String TAG_NAME = "service";

    private String type = TAG_NAME;

    private String name;

    @Override
    public String serializeXml(String prefix) {
        if(StrUtil.isEmpty(name)){
            return null;
        }
        return MPUtils.str(prefix, "<", TAG_NAME, " name=\"", name, "\"/>");
    }

    public static ServiceRule deserializeXml(String xml){
        if(StrUtil.isEmpty(xml)){
            return null;
        }
        try {
            Document document = DocumentHelper.parseText(xml);
            Element rootElement = document.getRootElement();
            return deserializeXml(rootElement);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static ServiceRule deserializeXml(Element xml){
        if(xml == null || !xml.getName().equalsIgnoreCase(TAG_NAME)){
            return null;
        }

        ServiceRule rule = new ServiceRule();
        rule.name = xml.attributeValue("name");
        return rule;
    }
}
